//
//  RecommendContentViewController.m
//  网络FM
//
//  Created by dllo on 15/5/25.
//  Copyright (c) 2015年 dengzhicheng.com. All rights reserved.
//

#import "RecommendContentViewController.h"
#import <AFNetworking.h>
#import "RecommendContentModel.h"
#import "RecommendContentTableViewCell.h"
#import "PlayerViewController.h"
#import <UIImageView+WebCache.h>
#import "GFPlaceholderView.h"
#import <MJRefresh.h>
#import "HistoryModel.h"
#import "HistoryDatabase.h"
static CGFloat kImageOriginHight = 160;
static CGFloat kTempHeight = 30.0f;
@interface RecommendContentViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)UIImageView *headerImage;
@property (nonatomic, retain)NSMutableArray *bigArray;
@property (nonatomic, assign) NSInteger pageChanged;
@property (nonatomic, retain)GFPlaceholderView *placeholder;
@end

@implementation RecommendContentViewController
- (void)dealloc
{
    [_pagenum release];
    [_pid release];
    [_contentTitle release];
    [_bigArray release];
    [_placeholder release];
    [_compere release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.bigArray = [NSMutableArray array];
        self.pageChanged = 2;
    }
    return self;
}
- (void)contentTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    self.tableView.separatorColor = [UIColor clearColor];
     self.tableView.contentInset = UIEdgeInsetsMake(kImageOriginHight, 0, 0, 0);
    
    self.headerImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, -kImageOriginHight - kTempHeight, self.tableView.frame.size.width, kImageOriginHight + kTempHeight)];
    [_headerImage sd_setImageWithURL:[NSURL URLWithString:self.titleImage] placeholderImage:[UIImage imageNamed:@"占位图.jpg"]];
    [self.tableView addSubview:self.headerImage];
    

    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(Load)];
    
    [self.view addSubview:_tableView];
    [_tableView release];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat yOffset  = scrollView.contentOffset.y;
    CGFloat xOffset = (yOffset + kImageOriginHight) / 2;
    if (yOffset < -kImageOriginHight) {
        CGRect f = self.headerImage.frame;
        f.origin.y = yOffset - kTempHeight;
        f.size.height =  -yOffset + kTempHeight;
        f.origin.x = xOffset;
        f.size.width = self.view.frame.size.width  +    fabs(xOffset)*2;
        self.headerImage.frame = f;
    }
}
- (void)loadView
{
    [super loadView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    // 自定义导航栏返回按钮
    UIButton *navButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [navButton addTarget:self action:@selector(navButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [navButton setImage:[UIImage imageNamed:@"返回.jpg"] forState:UIControlStateNormal];
    [navButton setImage:[UIImage imageNamed:@"返回.jpg"] forState:UIControlStateHighlighted];
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:navButton]];

    
    //等待界面
    self.placeholder = [[GFPlaceholderView alloc] initWithFrame:CGRectMake(0, - 64, self.view.frame.size.width, self.view.frame.size.height)];
    [_placeholder showLoadingView];
    [self.view addSubview:_placeholder];
    
    [self recommendConnection];
    self.navigationItem.title = self.contentTitle;
    // Do any additional setup after loading the view.
}

// 导航栏返回按钮点击事件
- (void)navButtonClick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -
#pragma mark 下拉加载
- (void)Load
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];


    NSString *str = [NSString stringWithFormat:@"http://d.fm.ifeng.com/fm/read/fmd/ios/600/getProgramAudioList.html?appid=TRWLY&listorder=desc&pid=%@&token=KhwbSbnG7FGcDnFn&pagenum=%ld", self.pid, (long)_pageChanged];

    [manager POST:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *string = [[NSString alloc] initWithFormat:@"%@", [bigDic objectForKey:@"data"]];
        if ([string isEqual:@""]) {
            [self contentTableView];
        } else {
            NSMutableDictionary *dic = [bigDic objectForKey:@"data"];
            
            NSMutableArray *array = [dic objectForKey:@"list"];
            if (array.count == 0) {
                [self.tableView removeFooter];
                return ;
            }
            for (NSDictionary *dic in array) {
                RecommendContentModel *model = [[RecommendContentModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.bigArray addObject:model];
            }
            self.pageChanged += 1;
            [self.tableView.footer endRefreshing];
            [self.tableView reloadData];
        }
    } failure:
     ^(AFHTTPRequestOperation *operation, NSError *error) {
         [self.tableView.footer endRefreshing];
     }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.bigArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"contentCell";
    RecommendContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (!cell) {
        cell = [[RecommendContentTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:str];
    }
    RecommendContentModel *model = [self.bigArray objectAtIndex:indexPath.row];
    [cell.titleLable setText:model.title];
    [cell.likeImageView setImage:[UIImage imageNamed:@"喜欢.png"]];
    NSString *string = [NSString stringWithFormat:@"%@",model.collectNumShow];
    [cell.likeLable setText:string];
    [cell.aImageView setImage:[UIImage imageNamed:@"列表播放图片.png"]];
    
    if (indexPath.row % 2) {
        
        cell.frame = CGRectMake(-320, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        
        [UIView animateWithDuration:0.7 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        } completion:^(BOOL finished) {
            ;
        }];
        
    }
    else{
        
        cell.frame = CGRectMake(320 ,cell.frame.origin.y ,cell.frame.size.width, cell.frame.size.height);
        
        [UIView animateWithDuration:0.7 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        } completion:^(BOOL finished) {
            ;
        }];
        
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
#pragma mark -
#pragma mark 数据请求
- (void)recommendConnection
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [NSString stringWithFormat:@"http://d.fm.ifeng.com/fm/read/fmd/ios/600/getProgramAudioList.html?appid=TRWLY&listorder=desc&pid=%@&token=KhwbSbnG7FGcDnFn&pagenum=1", self.pid];
    [manager POST:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *string = [[NSString alloc] initWithFormat:@"%@", [bigDic objectForKey:@"data"]];
        if ([string isEqual:@""]) {
            [self contentTableView];
        } else {
        NSMutableDictionary *dic = [bigDic objectForKey:@"data"];

        NSMutableArray *array = [dic objectForKey:@"list"];
        for (NSDictionary *dic in array) {
            RecommendContentModel *model = [[RecommendContentModel alloc] init];
            NSString * str = [dic objectForKey:@"videoUrl"];
            if (![str isEqual:@""]) {
                [model setValuesForKeysWithDictionary:dic];
                [self.bigArray addObject:model];
            } else {
                [model setValuesForKeysWithDictionary:dic];
                NSMutableArray *arr = [dic objectForKey:@"audiolist"];
                NSMutableDictionary *dic1 = [arr firstObject];
                model.videoUrl = [dic1 objectForKey:@"filePath"];
                [self.bigArray addObject:model];
            }
        }
        [self contentTableView];
        }
    } failure:
     ^(AFHTTPRequestOperation *operation, NSError *error) {
         
     }];
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
    PlayerViewController *player = [[PlayerViewController alloc] init];
    RecommendContentModel *model = [self.bigArray objectAtIndex:indexPath.row];
    
    
    
    HistoryModel *model1 = [[HistoryModel alloc] init];
    model1.titleName = model.title;
    model1.imageName = model.middlePictureUrl;
    model1.videoUrl = model.videoUrl;
    model1.people = self.compere;
    [HistoryDatabase insertWithModel:model1];
    
    player.urlForPlay = model.videoUrl;
    player.picURL = model.middlePictureUrl;
    player.tit = model.title;
    player.speaker = self.compere;
    
    
    
    UIView *controlView = [self.view.window.subviews objectAtIndex:1];
    [controlView setAlpha:0];
    
    [self.navigationController pushViewController:player animated:YES];
    [player release];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
